package com.yiyi.credit.manage.sso.manager.common.handler;


import com.yiyi.credit.manage.sso.common.Constant;
import com.yiyi.credit.manage.sso.common.CookieConstants;
import com.yiyi.credit.manage.sso.common.utils.CookieUtils;
import com.yiyi.credit.manage.sso.model.dto.response.SpApiResponse;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;


@Aspect
@Component
public class LoginHandler {

    @Autowired
    UserManagerClient userManagerClient;

    private static final Set<String> ANONYMOUS_ACCESS_URI_SET = new HashSet<>();

    static {
        ANONYMOUS_ACCESS_URI_SET.add("/manager/loginSysUser");
    }

    private static final String LOGIN_URI = "/login";

    @Pointcut("execution(* com.yiyi.credit.manage.sso.manager.controller..*.*(..))")
    public void executeService() {

    }

    @Around("executeService()")
    public Object invoke(final ProceedingJoinPoint thisJoinPoint) throws Throwable {

        HttpServletRequest request =
            ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

        String uri = request.getRequestURI();
        if (ANONYMOUS_ACCESS_URI_SET.contains(uri)) {
            return thisJoinPoint.proceed();
        }

        //SpApiResponse spApiResponse = userManagerClient.getTokenKey();
        // cookie获取token值
        String token = CookieUtils.getCookieByName(request.getCookies(), CookieConstants.NAME);

        return checkTokenAccess(thisJoinPoint, uri, token);
    }


    private Object checkTokenAccess(ProceedingJoinPoint thisJoinPoint, String uri,
                                    String token) throws Throwable {
        // 校验token
        if (StringUtils.isNotBlank(token)) {
            SpApiResponse spApiResponse = userManagerClient.authToken(token);
            if (spApiResponse.getCode().equals(Constant.SUCCESS_CODE)) {
                if (uri.equals(LOGIN_URI)) {
                    return new ModelAndView("/manager/manager");
                }
                return thisJoinPoint.proceed();
            }
        }
        return new ModelAndView(LOGIN_URI);
    }
}
